import { useEffect, useCallback, useRef } from 'react';
/**
 * 节流函数
 * @param func 要进行节流的指标函数
 * @param delay 节流的工夫距离（毫秒）
 * @returns 返回一个通过节流解决的函数
 */
export const throttle = <T extends (...args: any[]) => any>(
  fn: T,
  delay: number
): T => {
  let lastCall: number | null = null; // 上一次调用的工夫戳

  return function (
    this: ThisParameterType<T>,
    ...args: Parameters<T>
  ): ReturnType<T> | void {
    const now = Date.now(); //以后工夫戳
    // 如果之前没有调用过,或者工夫距离超过了设定的值,执行指标函数
    if (!lastCall || now - lastCall >= delay) {
      lastCall = now;
      return fn.apply(this, args);
    }
  } as T;
};

export function useThrottle(fn, delay: any, dep = []) {
  const { current } = useRef<any>({ fn, timer: null });
  useEffect(() => {
    current.fn = fn;
  }, [fn]);

  return useCallback(function f(this: any, ...args) {
    if (!current.timer) {
      current.timer = setTimeout(() => {
        delete current.timer;
      }, delay);
      current.fn.call(this, args);
    }
  }, dep);
}
export default throttle;
